package com.totoro.metrics;

import com.codahale.metrics.*;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

/**
 * Meterics值的发布方式
 * Created by Niki on 2018/8/28 14:37
 */
public class OutputUtil {
    /**
     * 采用Console的方式发布metrics值
     */
    public static void console(MetricRegistry metrics) {
        /**
         * 将监控结果打印到控制台
         */
        ConsoleReporter reporter = ConsoleReporter.forRegistry(metrics).build();
        reporter.start(3, TimeUnit.SECONDS);
    }

    /**
     * 采用JMX的方式发布metrics的值
     * 启动后，reporter中注册的metrics值都可以通过JConsole或者VisualVM查看
     */
    public static void jmx(MetricRegistry metrics) {
        JmxReporter reporter = JmxReporter.forRegistry(metrics).build();
        reporter.start();
    }

    /**
     * 采用CSV文件的形式保存metrics的值
     * @param metrics
     * @param csvFile
     */
    public static void csv(MetricRegistry metrics, File csvFile) {
        CsvReporter reporter = CsvReporter.forRegistry(metrics)
                .formatFor(Locale.CHINA)
                .convertRatesTo(TimeUnit.SECONDS)
                .convertDurationsTo(TimeUnit.MILLISECONDS)
                .build(csvFile);
        reporter.start(3, TimeUnit.SECONDS);
    }

    /**
     * 采用log的方式将metrics的值上报到项目的日志系统
     * @param metrics
     */
    public static void log(MetricRegistry metrics) {
        Slf4jReporter reporter = Slf4jReporter.forRegistry(metrics)
                //获取日志对象
                .outputTo(LoggerFactory.getLogger("com.totoro.xxx.Class"))
                .convertRatesTo(TimeUnit.SECONDS)
                .convertDurationsTo(TimeUnit.MILLISECONDS)
                .build();

        reporter.start(3, TimeUnit.SECONDS);
    }

}
